package com.gxm.练习.多线程.循环abc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @创建人 郭训民
 * @创建时间 2019/11/15
 * @描述
 */
public class AbcSemaphore {
    Semaphore semaphore1 = new Semaphore(0);
    Semaphore semaphore2 = new Semaphore(0);
    Semaphore semaphore3 = new Semaphore(0);
    public  void printAbc()  {
        ExecutorService exe = Executors.newCachedThreadPool();
        Thread t1 = new Thread(()-> {
            while (true){
                try {
                    semaphore1.acquire();
                    System.out.println("a");
                    semaphore2.release(); // semaphore2 + 1
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(()-> {
            while (true){
                try {
                    semaphore2.acquire();
                    System.out.println("b");
                    semaphore3.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t3 = new Thread(()-> {
            while (true){
                try {
                    semaphore3.acquire();
                    System.out.println("c");
                    semaphore1.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        exe.execute(t1);
        exe.execute(t2);
        exe.execute(t3);
    }

    public static void main(String[] args) {
        AbcSemaphore abcSemaphore = new AbcSemaphore();
        abcSemaphore.printAbc();
    }
}
